package appCommand

import (
	"strconv"
	"tushare/model/aliyun/ecs"

	"tushare/common"

	"github.com/gin-gonic/gin"
)

type AppManage struct{}

func (am AppManage) StartApp(c *gin.Context) {
	us := new(common.UserSession)
	userInfo := us.GetUserInfo(c)

	id, _ := strconv.ParseInt(c.Query("id"), 10, 64)

	appInfo := ecs.AliyunEcsAppInfoById(id)
	if appInfo.UserId != userInfo.Id {
		c.JSON(200, gin.H{"code": 1, "message": "app信息未找到"})
		c.Abort()
		return
	}

	ecsInfo := ecs.AliyunEcsByUserIdAndInstanceId(userInfo.Id, appInfo.InstanceId)

	if appInfo.AppName == "Nginx" {
		ams := new(AppManageShell)
		ams.StartNginx(ecsInfo.Ip)
	} else if appInfo.AppName == "Redis" {
		ams := new(AppManageShell)
		ams.StartRedis(ecsInfo.Ip)
	} else if appInfo.AppName == "Kafka" {
		ams := new(AppManageShell)
		ams.StartKafka(ecsInfo.Ip)
	}

	appInfo.Status = 1
	ecs.AliyunEcsAppUpdate(appInfo.Id, appInfo)

	c.JSON(200, gin.H{"code": 0, "message": "启动成功"})
}

func (am AppManage) StopApp(c *gin.Context) {
	us := new(common.UserSession)
	userInfo := us.GetUserInfo(c)

	id, _ := strconv.ParseInt(c.Query("id"), 10, 64)

	appInfo := ecs.AliyunEcsAppInfoById(id)
	if appInfo.UserId != userInfo.Id {
		c.JSON(200, gin.H{"code": 1, "message": "app信息未找到"})
		c.Abort()
		return
	}

	ecsInfo := ecs.AliyunEcsByUserIdAndInstanceId(userInfo.Id, appInfo.InstanceId)

	if appInfo.AppName == "Nginx" {
		ams := new(AppManageShell)
		ams.StopNginx(ecsInfo.Ip)
	} else if appInfo.AppName == "Redis" {
		ams := new(AppManageShell)
		ams.StopRedis(ecsInfo.Ip)
	}

	appInfo.Status = 3
	ecs.AliyunEcsAppUpdate(appInfo.Id, appInfo)

	c.JSON(200, gin.H{"code": 0, "message": "停止成功"})
}

func (am AppManage) ReloadApp(c *gin.Context) {
	us := new(common.UserSession)
	userInfo := us.GetUserInfo(c)

	id, _ := strconv.ParseInt(c.Query("id"), 10, 64)

	appInfo := ecs.AliyunEcsAppInfoById(id)
	if appInfo.UserId != userInfo.Id {
		c.JSON(200, gin.H{"code": 1, "message": "app信息未找到"})
		c.Abort()
		return
	}

	ecsInfo := ecs.AliyunEcsByUserIdAndInstanceId(userInfo.Id, appInfo.InstanceId)

	if appInfo.AppName == "Nginx" {
		ams := new(AppManageShell)
		ams.ReloadNginx(ecsInfo.Ip)
	}

	appInfo.Status = 3
	ecs.AliyunEcsAppUpdate(appInfo.Id, appInfo)

	c.JSON(200, gin.H{"code": 0, "message": "重启成功"})
}
